<template>
    <view class="form-section">
        <text class="text-2xl font-bold text-center block my-3">备孕信息</text>
        <text class="text-base text-content text-center block mb-8">
            这些信息将帮助我们更准确地预测您的排卵期和生育窗口
        </text>

        <view class="custom-form">
            <view class="form-item">
                <view class="form-label">
                    <text>上一次经期开始日期</text>
                    <text class="required">*</text>
                </view>
                <view class="date-picker" @tap="showCalendar = true">
                    <view class="date-input">
                        <text v-if="localFormData.lastPeriodDate && localFormData.lastPeriodDate"
                            >{{ formatDisplayDate(localFormData.lastPeriodDate) }}
                        </text>
                        <text v-else class="placeholder">请选择日期</text>
                        <u-icon name="calendar" color="#999" size="20"></u-icon>
                    </view>
                </view>
                <text class="text-sm text-muted mt-1"
                    >请选择您最近一次月经的第一天
                </text>
            </view>

            <view class="form-item">
                <view class="form-label">
                    <text>平均经期天数</text>
                    <text class="required">*</text>
                </view>
                <view class="number-input">
                    <u-input
                        v-model="localFormData.periodDuration"
                        type="number"
                        :border="true"
                        @change="onPeriodDurationChange"
                    ></u-input>
                    <view class="number-control">
                        <view class="control-btn" @click="adjustNumber('periodDuration', 1)">
                            <u-icon name="arrow-up" size="20" color="#666"></u-icon>
                        </view>
                        <view class="control-btn" @click="adjustNumber('periodDuration', -1)">
                            <u-icon name="arrow-down" size="20" color="#666"></u-icon>
                        </view>
                    </view>
                </view>
                <text class="text-sm text-muted mt-1"
                    >月经通常持续的天数（一般为3-7天）
                </text>
            </view>

            <view class="form-item">
                <view class="form-label">
                    <text>平均月经周期</text>
                    <text class="required">*</text>
                </view>
                <view class="number-input">
                    <u-input
                        v-model="localFormData.cycleDuration"
                        type="number"
                        :border="true"
                        @change="onCycleDurationChange"
                    ></u-input>
                    <view class="number-control">
                        <view class="control-btn" @click="adjustNumber('cycleDuration', 1)">
                            <u-icon name="arrow-up" size="20" color="#666"></u-icon>
                        </view>
                        <view class="control-btn" @click="adjustNumber('cycleDuration', -1)">
                            <u-icon name="arrow-down" size="20" color="#666"></u-icon>
                        </view>
                    </view>
                </view>
                <text class="text-sm text-muted mt-1"
                    >从一次月经开始到下一次月经开始的天数（一般为28天）
                </text>
            </view>
        </view>

        <u-calendar 
            v-model="showCalendar" 
            @change="onDateChange" 
            :max-date="today"
            mode="date"
            confirmText="确认"
            toolTip="选择日期"
            activeBgColor="#FF9FB5"
            rangeBgColor="rgba(255, 159, 181, 0.13)"
            rangeColor="#FF9FB5"
            btnType="primary"
        ></u-calendar>
    </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch, onMounted } from 'vue'
import dayjs from 'dayjs'

// 定义props
const props = defineProps({
    formData: {
        type: Object,
        required: true
    },
    today: {
        type: String,
        required: true
    }
})

// 定义emit
const emit = defineEmits(['update:formData', 'validate'])

// 日期选择器控制
const showCalendar = ref<boolean>(false)

// 本地表单数据
const localFormData = reactive({
    lastPeriodDate: '',
    periodDuration: 5,
    cycleDuration: 28
})

// 初始化本地数据
onMounted(() => {
    if (props.formData) {
        Object.assign(localFormData, props.formData)
        console.log('初始化本地数据:', localFormData)
    }
})

// 监听props变化，更新本地数据
watch(() => props.formData, (newVal) => {
    if (newVal) {
        // 防止循环更新，只有当值不同时才更新
        if (JSON.stringify(localFormData) !== JSON.stringify(newVal)) {
            Object.assign(localFormData, newVal)
            console.log('props变化，更新本地数据:', localFormData)
        }
    }
}, { deep: true, immediate: true })

// 监听本地数据变化，更新父组件数据
watch(localFormData, (newVal) => {
    console.log('本地数据变化，更新父组件:', newVal)
    emit('update:formData', { ...newVal })
    validateForm()
}, { deep: true })

// 日期选择回调
const onDateChange = (e: any): void => {
    console.log('日期选择回调:', e);
    // 根据uView UI文档，日期选择事件可能直接返回日期字符串，或者包含在对象的result属性中
    const dateValue = typeof e === 'string' ? e : (e && e.result ? e.result : null);
    
    if (dateValue) {
        console.log('选择的日期:', dateValue);
        localFormData.lastPeriodDate = dateValue;
        showCalendar.value = false; // 关闭日历
        // 不需要手动emit，watch会处理
    }
}

// 经期天数变化回调
const onPeriodDurationChange = (value: number): void => {
    localFormData.periodDuration = value;
    // 不需要手动emit，watch会处理
}

// 月经周期变化回调
const onCycleDurationChange = (value: number): void => {
    localFormData.cycleDuration = value;
    // 不需要手动emit，watch会处理
}

// 验证表单
const validateForm = (): void => {
    const isValid = 
        !!localFormData.lastPeriodDate &&
        localFormData.periodDuration >= 1 &&
        localFormData.periodDuration <= 15 &&
        localFormData.cycleDuration >= 21 &&
        localFormData.cycleDuration <= 45;
    
    emit('validate', isValid);
}

// 调整数值输入框
const adjustNumber = (field: string, change: number): void => {
    if (field === 'periodDuration') {
        let value = parseInt(localFormData.periodDuration.toString()) || 0;
        value += change;
        // 确保值在有效范围内
        localFormData.periodDuration = Math.max(1, Math.min(15, value));
    } else if (field === 'cycleDuration') {
        let value = parseInt(localFormData.cycleDuration.toString()) || 0;
        value += change;
        // 确保值在有效范围内
        localFormData.cycleDuration = Math.max(21, Math.min(45, value));
    }
    // 不需要手动emit，watch会处理
}

// 格式化日期显示（用于界面显示）
const formatDisplayDate = (dateString: string): string => {
    if (!dateString) return '';
    console.log('格式化日期:', dateString);
    return dayjs(dateString).format('YYYY-MM-DD');
}
</script>

<style lang="scss" scoped>
/* 自定义表单样式 */
.custom-form {
    width: 100%;
}

.form-item {
    margin-bottom: 30rpx;
}

.form-label {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 16rpx;
    display: flex;
    align-items: center;
}

.required {
    color: #ff5252;
    margin-left: 8rpx;
}

/* 日期选择器样式 */
.date-picker {
    width: 100%;
    cursor: pointer;
}

.date-input {
    width: 100%;
    height: 80rpx;
    border: 1px solid #eeeeee;
    border-radius: 8rpx;
    padding: 0 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #ffffff;
}

.placeholder {
    color: #999999;
}

/* 数字输入框样式 */
.number-input {
    position: relative;
    width: 100%;
}

.number-control {
    position: absolute;
    right: 8rpx;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    gap: 4rpx;
    z-index: 1;
}

.control-btn {
    width: 48rpx;
    height: 34rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.control-btn:active {
    background-color: #ffd6e0;
}
</style> 